<?php


namespace app\api\controller;

use app\admin\model\finance\extract\Week;
use app\admin\model\Management;
use app\common\controller\Api;
use think\Db;
use think\Cache;

class Ajax extends Api
{
    /**
     * 读取省市区数据,联动列表
     */
    public function area()
    {
        header('Access-Control-Allow-Origin:*');
        if(!$provincelist = Cache::get('provincelist')){
            $where['level'] = 1;
            $provincelist = Db::name('area')->where($where)->field('id,name as value')->select();
    //        $provincelist = array_column($provincelist,null ,'id');
            foreach ($provincelist as &$province)
            {
                $where['level'] = 2;
                $where['pid'] = $province['id'];
                $province['childs'] = Db::name('area')->where($where)->field('id,name as value')->select();
    //            $province['childs'] = array_column($province['childs'],null ,'id');
                foreach ($province['childs'] as &$area)
                {
                    $where['level'] = 3;
                    $where['pid'] = $area['id'];
                    $area['childs'] = Db::name('area')->where($where)->field('id,name as value')->select();
    //                $area['childs'] = array_column( $area['childs'],null ,'id');
                }
            }
            Cache::set('provincelist',$provincelist,0);//设置0永久缓存不过期
        }
        $this->success('', $provincelist);
    }
     /**
     * 获取学校
     */
    public function base_school($type = 1){
        header('Access-Control-Allow-Origin:*');
        if(!$base_school = Cache::get('baseschool')){
          $base_school = Db::name('base_school')->where('delete_status',1)->where('type',$type)->field('id,name as value')->order('weigh','desc')->select();
          foreach ($base_school as &$class){
                $where['school_id'] = $class['id'];
                $class['childs'] = Db::name('base_school_class')->where($where)->field('id,name as value')->order('weigh','desc')->select();
            }
            Cache::set('baseschool',$base_school,0);//设置0永久缓存不过期
        }
        $this->success('', $base_school);
    }
     /**
     * 获取学校
     */
    public function ques_school($ids = 0){
        header('Access-Control-Allow-Origin:*');
        if(!$info = Cache::get('queschool'.$ids)){
          $this->QuesSchoolmodel = new \app\admin\model\ques\School;
          $ques_school = $this->QuesSchoolmodel->field('id,school_id')->where(['volume_id'=>$ids])->order('weigh','desc')->select();
          $info = [];
          foreach ($ques_school as $key =>$class){
                $info[$key]['id'] = $class['id'].'-'.$class['school_id'];
                $info[$key]['value'] = $class['school_text'];
                $where['school_id'] = $class['school_id'];
                $info[$key]['childs'] = Db::name('base_school_class')->where($where)->field('id,name as value')->order('weigh','desc')->select();
            }
            Cache::set('queschool'.$ids,$info,0);//设置0永久缓存不过期
        }
        $this->success('', $info);
    }
     /**
     * 获取学校下班级
     */
    public function base_school_class($type = 1){
        header('Access-Control-Allow-Origin:*');
        if(!$info = Cache::get('baseschoolclass')){
          $base_school = Db::name('base_school')->where('delete_status',1)->where('type',$type)->field('id,name as value')->order('weigh','desc')->select();
          $info = [];
          $info[0] = [
            'text'=>'请选择',
            'classlist'=>[0=>['text'=>'请选择']],
          ];
          $arr = [0=>['text'=>'请选择']];
          foreach ($base_school as $key=>$class){
                $info[$key+1]['text'] = $class['value'];
                $where['school_id'] = $class['id'];
                $classlist = Db::name('base_school_class')->where($where)->field('name as text')->order('weigh','desc')->select();
                $info[$key+1]['classlist'] = array_merge($arr,$classlist);
                unset($classlist);
            }
            Cache::set('baseschoolclass',$info,0);//设置0永久缓存不过期
        }
        $this->success('', $info);
    }
    /**
     * 读取省市区数据,联动列表
     */
    public function area_zdy()
    {
        header('Access-Control-Allow-Origin:*');
        
        //上海 801
        //浙江 933
        $where_pr = "level = 1 and (id = 801 or id = 933)";
        $provincelist = Db::name('area')->where($where_pr)->field('id,name as value')->select();
//        $provincelist = array_column($provincelist,null ,'id');
        foreach ($provincelist as &$province)
        {
            $where_childs['level'] = 2;
            $where_childs['pid'] = $province['id'];
            if($province['id'] == 933){
                $where_childs['id'] =  934;
            }
            $province['childs'] = Db::name('area')->where($where_childs)->field('id,name as value')->select();
//            $province['childs'] = array_column($province['childs'],null ,'id');
            foreach ($province['childs'] as &$area)
            {
                $where['level'] = 3;
                $where['pid'] = $area['id'];
                $area['childs'] = Db::name('area')->where($where)->field('id,name as value')->select();
//                $area['childs'] = array_column( $area['childs'],null ,'id');
            }
        }
        $this->success('', $provincelist);
    }
    /**
     * 读取年 周
     */
    public function year(){
        header('Access-Control-Allow-Origin:*');
        $num = $this->request->get('num');
        $year = $this->request->get('year');
        $start_year = 2018;
        $yearArr = [];
        if ($year !== '') {
            if($year){
                $week = GetYearWeek($year);
                $a = 0;
                foreach($week as $key=>$val){
                    $yearArr[$a]['value'] = $val[0].','.$val[1];
                    $yearArr[$a]['name'] = '第'.$key.'周'.','.date('m.d',strtotime($val[0])).'~'.date('m.d',strtotime($val[1]));
                    $a++;
                }
            }
            if($num){
                $a = 0;
                for($i=$start_year; $i<=$start_year+$num; $i++){
                    $yearArr[$a]['value'] = $i;
                    $yearArr[$a]['name'] = $i.'年';
                    $a++;
                }
            }
        }
        $this->success('获取成功', $yearArr);
    }
    /**
     * 读取年 周 
     */
    public function year_week(){
        header('Access-Control-Allow-Origin:*');
         if ($this->request->isPost()) {
            $row = $this->request->post();
            $this->model = new \app\admin\model\finance\extract\Week;
            $where =  " `status` not in(-1,0,1) ";
            $result = [0=>['value'=>0,'name'=>'全部']];
            $result_key = 1;
            switch ($row['type']) {
                case 3:
                      $result = [];
                      $result_key = 0;
                      $where .= " and (`status` = 2  or `status` = -2) ";
                    # code...
                    break;      
                 case 1:
                     $result = [];
                       $result_key = 0;
                    # code...
                    break;
                default:
                    # code...
                    break;
            }
            if($row['department']){
               $where .=  " and `department` = ".$row['department'];
            }
            $list = $this->model
                ->where($where)
                ->group('year')
                ->select();
             $list = collection($list)->toArray();
             $year = '';
             $week = '';
             $week_true = 0;
             $week_more = 0;
             $year_more = $result_key;
             $week_fales = 0;
             if(isset($row['year'])){
                $year = $row['year'];
                 if(isset($row['week_text'])){
                    $week = $row['week_text'];
                 }
             }

             if(!empty($list)){
                foreach ($list as $key => $value) {
                    if($year == $value['year']){
                        $week_true = 1;
                        $year_more = $key+$result_key;
                    }
                      $result[$key+$result_key]['value'] = $value['year'];
                       $where .= " and `year` =".$value['year'];
                       $result[$key+$result_key]['name'] = $value['year'].'年';
                       $info = $this->model
                        ->where($where)
                        ->group('start_time')
                        ->select();
                      $info = collection($info)->toArray();
                      if(!empty($info)){
                        if($row['type'] == 3){
                          foreach ($info as $k => $v) {
                            if($week_true == 1 && $week == $v['week_text']){
                               $week_more = $k;
                               $week_fales = 1;
                              } 
                              $result[$key+$result_key]['childs'][$k]['value'] = $v['id'];
                              $result[$key+$result_key]['childs'][$k]['name'] = '第'.$v['week_text'].'周,'.date('m.d',strtotime($v['start_time'])).'~'.date('m.d',strtotime($v['end_time']));
                          }
                         }else{
                            foreach ($info as $k => $v) {
                              if($week_true == 1 && $week == $v['week_text']){ 
                                  $week_more = $k;
                                  $week_fales = 1;
                                }
                                  $result[$key+$result_key]['childs'][$k]['value'] = $v['start_time'].','.$v['end_time'];
                                  $result[$key+$result_key]['childs'][$k]['name'] = '第'.$v['week_text'].'周,'.date('m.d',strtotime($v['start_time'])).'~'.date('m.d',strtotime($v['end_time']));
                              }
                             
                         }
                          //如果没有匹配，默认周围最后一个
                          if(!$week_fales){
                            $week_more = count($info)-1;
                          }
                      }
                     unset($info);
                }
             }
               
         }
        $this->success('获取成功', ['year_more'=>$year_more,'week_more'=>$week_more,'data'=>$result]);
    }
   /**
     * 读取产品分类
     */
    public function cost()
    {
        header('Access-Control-Allow-Origin:*');
        $type = $this->request->get('type');
        $more = $this->request->post();
        $where['type'] = $type;
        $where['delete_status'] = 1;
        $base_cost = Db::name('base_cost')->where($where)->field('id as value,name')->order( 'weigh','desc')->select();
        if(isset($more['more'])){
            $cost_more = 0;
           foreach ($base_cost as $k => $v) {
                  if($more['more'] == $v['value'] ) $cost_more = $k;
            }
         $this->success('获取成功', ['cost_more'=>$cost_more,'data'=>$base_cost]); 
      }else{
        $this->success('获取成功', $base_cost);
      }
    }
    /**
     * 提分超市订单推送
     * @param null $order
     * @throws \think\Exception
     */
    public function orderAdd($order= null)
    {
        $shop = Db::connect([
            // 数据库类型
            'type'        => 'mysql',
            // 服务器地址
            'hostname'    => '47.93.51.61',
            // 数据库名
            'database'    => 'shop_fc62_com',
            // 数据库用户名
            'username'    => 'oahdyj',
            // 数据库密码
            'password'    => 'oahdyj',
            // 数据库编码默认采用utf8
            'charset'     => 'utf8',
        ]);
        $shopRow = $shop->table('ecs_order_info')->where(['order_id'=>$order])->find();
        $shopName = $shop->table('ecs_region')->field('group_concat(region_name) as region_name')->where('region_id','in',[$shopRow['province'],$shopRow['city'],$shopRow['district']])->find();
        $shopList = $shop->table('ecs_order_goods')->where(['order_id'=>$order])->select();
        $shopRow['goodsName'] = '';//商品名称
        $shopRow['num'] = 0;//商品数量
        $shopRow['goods_attr'] = '';//商品属性
        foreach ($shopList as $value)
        {
            $shopRow['goodsName'] .= $value['goods_name'].',';
            $shopRow['num'] += $value['goods_number'];
            $shopRow['goods_attr'] .= $value['goods_attr'].',';
        }
        $fieldArr['orderid'] = $shopRow['order_sn'];//订单编号
        $fieldArr['consignee'] = $shopRow['consignee'];//收件人
        $fieldArr['consigneePhone'] = $shopRow['mobile'];//收件人电话
        $fieldArr['consigneeAddress'] = $shopName['region_name'].$shopRow['address'];//收件人地址
        $fieldArr['goods'] = $shopRow['goodsName'];//商品名称
        $fieldArr['version'] = $shopRow['goods_attr'];//商品名称
        $fieldArr['num'] = $shopRow['num'];//数量
        $fieldArr['amount'] = $shopRow['goods_amount'];//金额
        $fieldArr['courierFees'] = $shopRow['shipping_fee'];//快递费用
        $fieldArr['deliveryForm'] = $shopRow['shipping_name'];//快递方式
        $fieldArr['salesman'] = $shopRow['to_buyer'];//业务员
        $fieldArr['courierBut'] = $shopRow['invoice_no'];//快递单号
        $fieldArr['orderStatus'] = '代发货';
        if($shopRow['pay_id'] == 7)
        {
            $fieldArr['wechat'] = $shopRow['money_paid'];//微信
        }else{
            $fieldArr['alipay'] = $shopRow['money_paid'];//支付宝
        }
        $fieldArr['orderStatus'] = '';//订单状态
        $fieldArr['ordertime'] = $shopRow['add_time'];//创建时间
        $fieldArr['payment'] = $shopRow['pay_name'];//支付方式
        $fieldArr['source'] = '提分超市';//来源
        Management::create($fieldArr);
    }

    /**
     * 读取产品分类
     */
    public function cate()
    {
        header('Access-Control-Allow-Origin:*');
        $where['type'] = 2;
        $where['pid'] = 0;
        $where['id'] = 8;
        $provincelist = Db::name('halt_cate')->where($where)->field('id,name as value')->select();
//        $provincelist = array_column($provincelist,null ,'id');
        foreach ($provincelist as &$province)
        {
            $where['pid'] = $province['id'];
            unset($where['id']);
            $province['childs'] = Db::name('halt_cate')->where($where)->field('id,name as value')->select();
//            $province['childs'] = array_column($province['childs'],null ,'id');
            foreach ($province['childs'] as &$area)
            {
                $where['pid'] = $area['id'];
                $area['childs'] = Db::name('halt_cate')->where($where)->field('id,name as value')->select();
//                $area['childs'] = array_column( $area['childs'],null ,'id');
            }
        }
        $this->success('', $provincelist);
    }


    /**
     * 外联任务单  获取开会周次
     */
    public function years(){
        header('Access-Control-Allow-Origin:*');
        $num = $this->request->get('num',10);
        $start_year = 2018;
        $yearArr = [];
        $a = 0;
        for($i=$start_year; $i<=$start_year+$num; $i++){
            $yearArr[$a]['id'] = $i;
            $yearArr[$a]['value'] = $i.'年';
            $yearArr[$a]['childs'] = $this->getWeek($i);
            $a++;
        }
        $this->success('获取成功', $yearArr);
    }

    /**
     * 获取分公司
     */
    public function branch()
    {
        header('Access-Control-Allow-Origin:*');
        $weekModel = new Week();
        $ResList = $weekModel->getDepartmentList();
        $list = [];
        foreach ($ResList as $key=>$value)
        {
            $list[] = ['id'=>$key,'value'=>$value];
        }
        $this->success('获取分公司',$list);
    }

    private function getWeek($year)
    {
        $week = GetYearWeek($year);
        $array = [];
        foreach($week as $key=>$val){
            $array[] = [
                'id' => $val[0].','.$val[1],
                'value' => '第'.$key.'周'.' '.date('m.d',strtotime($val[0])).'~'.date('m.d',strtotime($val[1]))
            ];
        }
        return $array;
    }
 
}